// Copyright  Author(https://github.com/LiuShuKu). All Rights Reserved.

// Copyright (c)  2024 LiuShuKu
// Project Name :   balance
// Author       :   liushuku@yeah.net

// Package mongo .
package mongo

import (
	"context"
	"sync"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/qiniu/qmgo"
)

var (
	mongoClient *qmgo.QmgoClient
)

var Client = &client{}

type client struct {
	mongoClient *qmgo.QmgoClient
	mu          sync.Mutex
}

// NewClient 获取mongo client
func (c *client) NewClient(ctx context.Context) (cli *qmgo.QmgoClient, err error) {
	var (
		uri        string
		db         string
		collection string
	)
	{
		c.mu.Lock()
		defer c.mu.Unlock()
	}
	{
		if c.mongoClient != nil {
			cli = c.mongoClient
			return
		}
	}
	// 从配置中获取URI、数据库和集合名称
	{
		uri = g.Cfg().MustGet(ctx, "database.mongo.uri").String()
		db = g.Cfg().MustGet(ctx, "database.mongo.db").String()
		collection = g.Cfg().MustGet(ctx, "database.mongo.collection").String()
	}

	// 验证配置项的有效性
	{
		if uri == "" || db == "" || collection == "" {
			g.Log().Errorf(ctx, "mongo配置项无效")
			return
		}
	}
	// 创建MongoDB客户端
	if cli, err = qmgo.Open(ctx, &qmgo.Config{Uri: uri, Database: db, Coll: collection}); err != nil {
		return
	}
	{
		c.mongoClient = cli
	}
	return
}
